#include"hsl.hpp"
#include<stdio.h>
using namespace hsl;

Server::Server()
{
	int iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
	if(iResult)
	{
		alert("Socket Create Error");
		throw SocketCreateError(SocketCreateError::Server);
	}
	ZeroMemory(&hints,sizeof hints);
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;
	iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
	if(iResult)
	{
		alert("getaddrinfo failed");
		WSACleanup();
		exit(1);
	}
	ListenSocket = socket(result->ai_family,result->ai_socktype,result->ai_protocol);
	if(ListenSocket == INVALID_SOCKET)
	{
		printf("Error at socket(): %ld\n",WSAGetLastError());
		freeaddrinfo(result);
    	WSACleanup();
    	exit(1);
	}
	iResult = bind(ListenSocket,result->ai_addr,(int)result->ai_addrlen);
	if(iResult == SOCKET_ERROR)
	{
		printf("bind failed with error: %d\n",WSAGetLastError());
		freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        exit(1);
	}
	freeaddrinfo(result);
	if(listen(ListenSocket,SOMAXCONN ) == SOCKET_ERROR)
	{
		printf( "Listen failed with error: %ld\n", WSAGetLastError() );
	    closesocket(ListenSocket);
	    WSACleanup();
	    exit(1);
	}
	do{
		ClientSocket = accept(ListenSocket,NULL,NULL);
	}while(ClientSocket == INVALID_SOCKET);
}










